import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Space,
  Input,
  Radio,
  Upload,
  Modal,
  message,
} from 'antd'
import { Link } from 'react-router-dom'
import { PlusOutlined } from '@ant-design/icons'
import Channel from 'pages/Channel'
import ReactQuill from 'react-quill'
import { baseURL } from 'utils/requset'
import 'react-quill/dist/quill.snow.css'
import style from './index.module.scss'
import { addArticles, getArticlesById, updateArticles } from 'api/articles'

export default class ArticlePublise extends Component {
  state = {
    type: 1,
    fileList: [],
    showPreview: false,
    previewUrl: '',
    id: this.props.match.params.id,
    backList: {},
  }
  formRef = React.createRef()
  render() {
    return (
      <div className={style.root}>
        <Card
          title={
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                {this.state.id ? '编辑文章' : '发布文章'}
              </Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            labelCol={{ span: 4 }}
            size="large"
            validateTrigger={['onBlur', 'onChange']}
            onFinish={this.onFinish}
            initialValues={{ content: '', type: this.state.type }}
            ref={this.formRef}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '文章标题不能为空' }]}
            >
              <Input
                style={{ width: 400 }}
                placeholder="请输入文章标题"
                autoComplete="off"
              ></Input>
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '请选择频道' }]}
            >
              <Channel></Channel>
            </Form.Item>
            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.onChangeFn}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              {this.state.type !== 0 && (
                <Upload
                  listType="picture-card"
                  fileList={this.state.fileList}
                  action={`${baseURL}/upload`}
                  name="image"
                  onChange={this.updateImg}
                  onPreview={this.handlePreview}
                  beforeUpload={this.beforeUpload}
                >
                  {this.state.fileList.length < this.state.type && (
                    <PlusOutlined />
                  )}
                </Upload>
              )}
            </Form.Item>
            <Form.Item
              label="内容"
              name="content"
              rules={[
                {
                  required: true,
                  message: '文章的内容不能为空',
                },
              ]}
            >
              <ReactQuill
                theme="snow"
                placeholder="请输入文章的内容"
              ></ReactQuill>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  {' '}
                  {this.state.id ? '编辑文章' : '发布文章'}
                </Button>
                <Button onClick={this.addDraft}>存入草稿</Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
        <Modal
          visible={this.state.showPreview}
          title="图片预览"
          footer={null}
          onCancel={this.handleCancel}
        >
          <img
            alt="example"
            style={{ width: '100%' }}
            src={this.state.previewUrl}
          />
        </Modal>
      </div>
    )
  }
  async componentDidMount() {
    if (this.state.id) {
      const res = await getArticlesById(this.state.id)
      // console.log(res)
      const fileList = res.data.cover.images.map((item) => ({ url: item }))
      const values = {
        ...res.data,
        type: res.data.cover.type,
      }
      console.log(this.formRef)
      this.formRef.current.setFieldsValue(values)
      this.setState({
        fileList,
      })
    }
  }
  beforeUpload = (file) => {
    console.log(file)
    if (file.size >= 1024 * 500) {
      message.warn('上传文件不能超过 500kb')
      return Upload.LIST_IGNORE
    }
    if (!['image/png', 'image/jpeg'].includes(file.type)) {
      message.warn('只能上传 jpg 和 png 格式图片')
      return Upload.LIST_IGNORE
    }
    return true
  }
  handleCancel = () => {
    this.setState({
      showPreview: false,
    })
  }
  handlePreview = (e) => {
    // console.log(e.response.data.url)
    const url = e.url || e.response.data.url
    this.setState({
      previewUrl: url,
      showPreview: true,
    })
  }
  save = async (values, draft) => {
    console.log(values)
    const { fileList, type, id } = this.state
    if (fileList.length !== type) {
      message.warn('图片的数量不符')
      return false
    }
    // console.log(fileList)
    const images = fileList.map((item) => {
      return item.url || item.response.data.url
    })
    // console.log(values)
    if (id) {
      await updateArticles({
        ...values,
        id,
        cover: {
          type,
          images,
        },
        draft,
      })
      message.success('修改成功')
    } else {
      await addArticles(
        {
          ...values,
          cover: {
            type,
            images,
          },
        },
        draft
      )
      message.success('发布成功')
    }

    this.props.history.push('/home/list')
  }
  onFinish = async (values) => {
    this.save(values, false)
  }
  addDraft = async () => {
    const values = await this.formRef.current.validateFields()
    this.save(values, true)
  }
  onChangeFn = (e) => {
    // console.log(e.target.value)
    this.setState({
      type: e.target.value,
      fileList: [],
    })
  }
  updateImg = ({ fileList }) => {
    this.setState({
      fileList,
    })
  }
}
